import json
from apps.common.base.models import BaseModel
from apps.common.base.serializers import BaseSerializer
from apps.system.log.models import Log
import datetime

class BaseDao:
    # 子类必须覆盖这个
    MODEL_CLASS = BaseModel
    SERI_CLASS = BaseSerializer
    SAVE_BATCH_SIZE = 1000

    # 增
    def create(self, data):
        if data.get('requestUserId'):
            data['createUser'] = data.get('requestUserId')
            data['createUsername'] = data.get('requestUsername')
        serializers = self.SERI_CLASS(data=data)
        if serializers.is_valid():
            serializers.save()
            # 插入日志
            if data.get('requestUserId'):
                r_data = {}
                r_data['byUser_id'] = data.get('requestUserId')
                r_data['tableName'] = self.MODEL_CLASS._meta.db_table
                r_data['recordId'] = serializers.data.get('id')
                r_data['newContent'] = json.dumps(data, indent=4, ensure_ascii=False)
                r_data['types'] = 'create'
                Log.objects.create(**r_data)
            return self.MODEL_CLASS.objects.get(id=serializers.data.get('id'))
        else:
            print('create --error--', self.MODEL_CLASS, serializers.errors)
            return serializers.errors
        
    # 逻辑删除
    def delete(self, obj_ids, data):
        objs = self.MODEL_CLASS.objects.filter(id__in=obj_ids)
        objs.update(is_delete=1, deleteTime=datetime.datetime.now())
        # 插入日志
        if data.get('requestUserId'):
            r_data = {}
            r_data['byUser_id'] = data.get('requestUserId')
            r_data['tableName'] = self.MODEL_CLASS._meta.db_table
            r_data['recordId'] = None
            r_data['newContent'] = json.dumps(obj_ids)
            r_data['types'] = 'delete'
            Log.objects.create(**r_data)

    # 物理删除
    def real_delete(self, obj_ids, data):
        objs = self.MODEL_CLASS.objects.filter(id__in=obj_ids)
        objs.delete()
        # 插入日志
        if data.get('requestUserId'):
            r_data = {}
            r_data['byUser_id'] = data.get('requestUserId')
            r_data['tableName'] = self.MODEL_CLASS._meta.db_table
            r_data['recordId'] = None
            r_data['newContent'] = json.dumps(obj_ids)
            r_data['types'] = 'real_delete'
            Log.objects.create(**r_data)

    # 改
    def update(self, obj_id, data):
        try:
            obj = self.MODEL_CLASS.objects.get(id=obj_id)
            data['updateTime'] = str(datetime.datetime.now())
            data.pop('createUser', None) # 更新的时候不序列化createUser字段
            serializers = self.SERI_CLASS(obj, data=data, partial=True)
            oldData = self.SERI_CLASS(obj).data
            if serializers.is_valid():
                serializers.save()
                # 插入日志
                if data.get('requestUserId'):
                    r_data = {}
                    r_data['byUser_id'] = data.get('requestUserId')
                    r_data['tableName'] = self.MODEL_CLASS._meta.db_table
                    r_data['recordId'] = serializers.data.get('id')
                    r_data['oldContent'] = json.dumps(oldData, indent=4, ensure_ascii=False)
                    r_data['newContent'] = json.dumps(data, indent=4, ensure_ascii=False)
                    r_data['types'] = 'update'
                    Log.objects.create(**r_data)
                return self.MODEL_CLASS.objects.get(id=obj_id)
            else:
                print('update--error----', self.MODEL_CLASS, serializers.errors)
                return serializers.errors
        except self.MODEL_CLASS.DoesNotExist:
            print(self.MODEL_CLASS, '记录不存在')
            return False
        
    # 查单个实例
    def findOneByObjId(self, obj_id):
        try:
            obj = self.MODEL_CLASS.objects.get(id=obj_id)
            return obj
        except self.MODEL_CLASS.DoesNotExist:
            print(self.MODEL_CLASS, '记录不存在')
            return False

    # 批量创建，dicts为字典列表
    def bulk_create(self, dicts, batch_size=SAVE_BATCH_SIZE):
        _list = list()
        for dict in dicts:
            _list.append(self.MODEL_CLASS(**dict))
        objs = self.MODEL_CLASS.objects.bulk_create(_list, batch_size=batch_size)
        return objs
    
    # 查询所有
    def findAll(self):
        objs = self.MODEL_CLASS.objects.order_by('-sort', '-id')
        return objs

    # 条件查询
    def findAllByFilter(self, filter_kw: dict, exclude_kw: dict, order_bys: list) -> list:
        return self.MODEL_CLASS.objects.filter(**filter_kw).exclude(**exclude_kw).order_by(*order_bys)